class ConsultationBooking {
    constructor() {
        this.currentRoom = null;
        this.selectedDate = new Date();
        this.selectedTime = null;
        this.bookingData = new Map();
        
        this.init();
    }

    async init() {
        this.showLoading();
        try {
            await this.loadRoomsStatus();
            this.initModalEvents();
            this.initDateNavigation();
        } catch (error) {
            this.showToast('加载数据失败，请刷新重试');
            console.error('初始化失败:', error);
        } finally {
            this.hideLoading();
        }
    }

    async loadRoomsStatus() {
        try {
            const response = await fetch('booking.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    action: 'getRooms'
                })
            });

            const data = await response.json();
            if (data.success) {
                this.bookingData.clear();
                data.rooms.forEach(room => {
                    this.bookingData.set(room.id, {
                        info: room,
                        timeSlots: null
                    });
                });
                await this.renderRooms(data.rooms);
            } else {
                throw new Error(data.message);
            }
        } catch (error) {
            console.error('获取房间状态失败:', error);
            throw error;
        }
    }

    async renderRooms(rooms) {
        const container = document.querySelector('.rooms-container');
        container.innerHTML = rooms.map(room => this.createRoomCard(room)).join('');

        for (const room of rooms) {
            await this.updateRoomTimeSlots(room.id);
        }

        document.querySelectorAll('.book-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const roomId = e.target.closest('.room-card').id.replace('room', '');
                this.openBookingModal(roomId);
            });
        });
    }

    async loadTimeSlots(roomId, date) {
        try {
            const response = await fetch('booking.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    action: 'getTimeSlots',
                    roomId: roomId,
                    date: this.formatDateForServer(date)
                })
            });

            const data = await response.json();
            if (!data.success) {
                throw new Error(data.message || '加载失败');
            }

            // 确保数据格式正确
            const timeSlots = Array.isArray(data.timeSlots) ? data.timeSlots : [];
            
            // 更新缓存
            const roomData = this.bookingData.get(parseInt(roomId)) || {};
            roomData.timeSlots = timeSlots;
            this.bookingData.set(parseInt(roomId), roomData);

            return timeSlots;
        } catch (error) {
            console.error('获取时间段失败:', error);
            throw error;
        }
    }

    async handleBookingConfirmation() {
        if (!this.selectedTime) {
            this.showToast('请选择预约时间');
            return;
        }

        this.showLoading();
        try {
            // 获取最新时间段数据
            const timeSlots = await this.loadTimeSlots(this.currentRoom, this.selectedDate);
            
            // 检查选中的时间段是否可用
            const selectedSlot = timeSlots.find(slot => slot.time === this.selectedTime);
            if (!selectedSlot || !selectedSlot.available) {
                this.showToast('该时段已被预约，请重新选择');
                await this.updateModalTimeSlots();
                return;
            }

            const response = await fetch('booking.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    action: 'book',
                    roomId: this.currentRoom,
                    date: this.formatDateForServer(this.selectedDate),
                    time: this.selectedTime
                })
            });

            const result = await response.json();
            if (result.success) {
                // 更新本地缓存中的时间段状态
                const roomData = this.bookingData.get(parseInt(this.currentRoom));
                if (roomData && roomData.timeSlots) {
                    const slotIndex = roomData.timeSlots.findIndex(slot => slot.time === this.selectedTime);
                    if (slotIndex !== -1) {
                        roomData.timeSlots[slotIndex].available = false;
                    }
                }
                
                this.showToast('预约成功！');
                this.closeModal();
                // 重新加载所有房间状态
                await this.loadRoomsStatus();
            } else {
                this.showToast(result.message || '预约失败，请重试');
            }
        } catch (error) {
            this.showToast('系统错误，请稍后重试');
            console.error('预约失败:', error);
        } finally {
            this.hideLoading();
        }
    }

    createRoomCard(room) {
        return `
            <div class="room-card" id="room${room.id}">
                <div class="room-header">
                    <h2>${room.name}</h2>
                    <span class="room-status ${room.availableSlots > 0 ? 'available' : 'unavailable'}">
                        ${room.availableSlots > 0 ? '当前可预约' : '暂不可约'}
                    </span>
                </div>
                <div class="room-info">
                    <div class="info-item">
                        <span class="label">今日空闲</span>
                        <span class="value">${room.availableSlots}个时段</span>
                    </div>
                    <div class="info-item">
                        <span class="label">下个空闲</span>
                        <span class="value">${room.nextAvailable || '暂无'}</span>
                    </div>
                </div>
                <div class="room-schedule">
                    <div class="schedule-title">今日时段</div>
                    <div class="time-slots" id="slots${room.id}">
                        <div class="loading-slots">加载中...</div>
                    </div>
                </div>
                <button class="book-btn" ${room.availableSlots === 0 ? 'disabled' : ''}>
                    立即预约
                </button>
            </div>
        `;
    }

    async updateRoomTimeSlots(roomId) {
        const slotsContainer = document.getElementById(`slots${roomId}`);
        if (!slotsContainer) return;

        try {
            slotsContainer.innerHTML = '<div class="loading-slots">加载中...</div>';
            const timeSlots = await this.loadTimeSlots(roomId, this.selectedDate);
            
            // 确保时间段数据正确
            if (!Array.isArray(timeSlots)) {
                throw new Error('无效的时间段数据');
            }

            requestAnimationFrame(() => {
                slotsContainer.style.opacity = '0';
                const html = this.renderTimeSlots(timeSlots);
                slotsContainer.innerHTML = html;
                
                requestAnimationFrame(() => {
                    slotsContainer.style.opacity = '1';
                });

                // 只为可预约的时段添加点击事件
                slotsContainer.querySelectorAll('.time-slot.available').forEach(slot => {
                    slot.addEventListener('click', () => {
                        if (!slot.classList.contains('booked')) {
                            this.handleTimeSelection(slot);
                        }
                    });
                });
            });
        } catch (error) {
            console.error(`加载房间 ${roomId} 时间段失败:`, error);
            slotsContainer.innerHTML = '<div class="error-slots">加载失败，点击重试</div>';
            slotsContainer.querySelector('.error-slots').onclick = () => {
                this.updateRoomTimeSlots(roomId);
            };
        }
    }

    renderTimeSlots(timeSlots) {
        if (!Array.isArray(timeSlots) || timeSlots.length === 0) {
            return '<div class="empty-slots">暂无可用时段</div>';
        }

        // 按时间段分组
        const morningSlots = timeSlots.filter(slot => slot.period === 'morning');
        const afternoonSlots = timeSlots.filter(slot => slot.period === 'afternoon');

        return `
            <div class="time-slots-container">
                ${morningSlots.length > 0 ? `
                    <div class="period-title">上午</div>
                    <div class="time-slots-grid">
                        ${this.renderTimeSlotGroup(morningSlots)}
                    </div>
                ` : ''}
                
                ${afternoonSlots.length > 0 ? `
                    <div class="period-title">下午</div>
                    <div class="time-slots-grid">
                        ${this.renderTimeSlotGroup(afternoonSlots)}
                    </div>
                ` : ''}
            </div>
        `;
    }

    renderTimeSlotGroup(slots) {
        return slots.map(slot => {
            const isAvailable = slot.available === true;
            return `
                <div class="time-slot ${isAvailable ? 'available' : 'booked'}" 
                     data-time="${slot.time}"
                     data-period="${slot.period}"
                     ${!isAvailable ? 'disabled' : ''}
                     style="pointer-events: ${isAvailable ? 'auto' : 'none'}">
                    <span class="time-text">${slot.time}</span>
                    <span class="status-text ${isAvailable ? '' : 'booked'}">
                        ${isAvailable ? '可预约' : '已预约'}
                    </span>
                </div>
            `;
        }).join('');
    }

    async openBookingModal(roomId) {
        this.currentRoom = parseInt(roomId);
        const modal = document.getElementById('bookingModal');
        modal.style.display = 'block';
        document.body.style.overflow = 'hidden';

        const roomName = document.querySelector(`#room${roomId} h2`).textContent;
        modal.querySelector('.room-name').textContent = roomName;

        await this.updateModalTimeSlots();
    }

    async updateModalTimeSlots() {
        const morningGrid = document.querySelector('.time-grid.morning');
        const afternoonGrid = document.querySelector('.time-grid.afternoon');

        morningGrid.innerHTML = '<div class="loading-slots">加载中...</div>';
        afternoonGrid.innerHTML = '<div class="loading-slots">加载中...</div>';

        try {
            const timeSlots = await this.loadTimeSlots(this.currentRoom, this.selectedDate);
            
            const morningSlots = timeSlots.filter(slot => slot.period === 'morning');
            const afternoonSlots = timeSlots.filter(slot => slot.period === 'afternoon');

            morningGrid.innerHTML = this.renderModalTimeSlots(morningSlots);
            afternoonGrid.innerHTML = this.renderModalTimeSlots(afternoonSlots);
        } catch (error) {
            morningGrid.innerHTML = '<div class="error-slots">加载失败</div>';
            afternoonGrid.innerHTML = '<div class="error-slots">加载失败</div>';
        }
    }

    renderModalTimeSlots(slots) {
        return slots.map(slot => `
            <div class="time-slot ${slot.available ? 'available' : 'booked'}" 
                 data-time="${slot.time}">
                ${slot.time}
                ${slot.available ? '' : '<span class="booked-tag">已预约</span>'}
            </div>
        `).join('');
    }

    initModalEvents() {
        const modal = document.getElementById('bookingModal');
        
        modal.querySelector('.close-btn').addEventListener('click', () => {
            this.closeModal();
        });

        modal.querySelector('.cancel-btn').addEventListener('click', () => {
            this.closeModal();
        });

        modal.querySelector('.confirm-btn').addEventListener('click', () => {
            this.handleBookingConfirmation();
        });

        modal.addEventListener('click', (e) => {
            if (e.target === modal) {
                this.closeModal();
            }
        });

        modal.querySelectorAll('.time-grid').forEach(grid => {
            grid.addEventListener('click', (e) => {
                if (e.target.classList.contains('time-slot')) {
                    this.handleTimeSelection(e.target);
                }
            });
        });
    }

    initDateNavigation() {
        const prevBtn = document.querySelector('.date-nav-btn.prev');
        const nextBtn = document.querySelector('.date-nav-btn.next');
        const currentDateSpan = document.querySelector('.current-date');

        if (prevBtn && nextBtn && currentDateSpan) {
            prevBtn.addEventListener('click', () => this.changeDate(-1));
            nextBtn.addEventListener('click', () => this.changeDate(1));
            this.updateDateDisplay();
        }
    }

    async changeDate(offset) {
        const newDate = new Date(this.selectedDate);
        newDate.setDate(newDate.getDate() + offset);
        
        // 不允许选择过去的日期
        if (newDate < new Date().setHours(0,0,0,0)) {
            this.showToast('不能选择过去的日期');
            return;
        }

        this.selectedDate = newDate;
        this.updateDateDisplay();
        
        // 更新时间段显示
        if (this.currentRoom) {
            await this.updateModalTimeSlots();
        }
    }

    updateDateDisplay() {
        const currentDateSpan = document.querySelector('.current-date');
        if (currentDateSpan) {
            currentDateSpan.textContent = this.formatDateForDisplay(this.selectedDate);
        }
    }

    formatDateForServer(date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    }

    parseDate(dateString) {
        const [year, month, day] = dateString.split('-').map(Number);
        return new Date(year, month - 1, day);
    }

    formatDateForDisplay(date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}年${month}月${day}日`;
    }

    showLoading() {
        const loading = document.createElement('div');
        loading.className = 'loading-overlay';
        loading.innerHTML = '<div class="loading-spinner"></div>';
        document.body.appendChild(loading);
        
        loading.offsetHeight;
        loading.classList.add('show');
    }

    hideLoading() {
        const loading = document.querySelector('.loading-overlay');
        if (loading) {
            loading.classList.remove('show');
            setTimeout(() => loading.remove(), 300);
        }
    }

    closeModal() {
        const modal = document.getElementById('bookingModal');
        modal.style.display = 'none';
        document.body.style.overflow = '';
        this.selectedTime = null;
    }

    showToast(message) {
        const toast = document.createElement('div');
        toast.className = 'toast';
        toast.textContent = message;
        document.body.appendChild(toast);

        setTimeout(() => toast.classList.add('show'), 10);
        
        setTimeout(() => {
            toast.classList.remove('show');
            setTimeout(() => toast.remove(), 300);
        }, 3000);
    }

    handleTimeSelection(timeSlot) {
        if (timeSlot.classList.contains('booked') || timeSlot.hasAttribute('disabled')) {
            return;
        }
        
        const allSlots = document.querySelectorAll('.time-slot');
        allSlots.forEach(slot => {
            slot.classList.remove('selected');
            slot.style.animation = '';
        });
        
        timeSlot.classList.add('selected');
        timeSlot.style.animation = 'selectPulse 0.3s ease';
        this.selectedTime = timeSlot.dataset.time;
    }
}

document.addEventListener('DOMContentLoaded', () => {
    new ConsultationBooking();
}); 